from rest_framework.viewsets import ModelViewSet
from goods.models import SKU, GoodsCategory, SPU, SPUSpecification
from meiduo_admin.utils import MyNumbPage
from .serializers import SkuViewSerialzer, CategoriesSerializer, SPUSerializer, SPUSpecificationSerializer
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.generics import ListAPIView, GenericAPIView
from rest_framework.views import APIView


class SkusViewSet(ModelViewSet):
    serializer_class = SkuViewSerialzer
    queryset = SKU.objects.order_by('id').all()
    pagination_class = MyNumbPage

    @action(methods=['get'], detail=False)
    def categories(self, request):
        categories = GoodsCategory.objects.filter(subs=None).all()
        serializer = CategoriesSerializer(instance=categories, many=True)
        return Response(serializer.data)

    # /skus/simple
    @action(methods=['get'], detail=False)
    def simple(self, requset):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class GoodsSimple(ListAPIView):
    serializer_class = SPUSerializer
    queryset = SPU.objects.all()


class GoodsSpecsView(ListAPIView):
    serializer_class = SPUSpecificationSerializer

    def get_queryset(self):
        pk = self.kwargs.get('pk')

        if pk:
            spu = SPU.objects.get(pk=pk)
            return spu.specs
        else:
            return SPU.objects.all()
